import React, { useState } from 'react';
import { View, Text} from '@tarojs/components';
import { SectionDescriptionTran, SectionIcon } from "@/constants/constants";
import {Close, Minus, Plus} from "@taroify/icons";
import {Button, Cell, List} from "@taroify/core";
import RefInput from "./refInput";

interface GenericMultipleSectionProps {
  contentData: {
    subSectionType: string;
    content: string[];
  };
  onChange: (newData: any) => void;
  onRemove: () => void;
  active: boolean;
}

const GenericMultipleSection: React.FC<GenericMultipleSectionProps> = ({ contentData, onChange, onRemove, active }) => {
  const [items, setItems] = useState(contentData.content);

  // Handle input changes
  const handleItemsChange = (index: number, value: string) => {
    const updatedItems = [...items];
    updatedItems[index] = value;
    setItems(updatedItems);
    onChange({ ...contentData, content: updatedItems });
  };

  // Handle removing items
  const handleRemoveItems = (index: number) => {
    const updatedItems = [...items];
    updatedItems.splice(index, 1);
    setItems(updatedItems);
    onChange({ ...contentData, content: updatedItems });
  };

  // Handle adding items
  const handleAddItems = () => {
    const updatedItems = [...items];
    updatedItems.push("");
    setItems(updatedItems);
    onChange({ ...contentData, content: updatedItems });
  };

  // Handle section remove
  const handleRemove = () => {
    onRemove();
  };

  const IconComponent = SectionIcon[contentData.subSectionType];

  return (
    <View>
      <View style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <View style={{ display: 'flex', alignItems: 'center' }}>
          <IconComponent />
          <Text className='subsection-title' style={{ marginLeft: 8, fontSize: '16px' }}>
            {SectionDescriptionTran[contentData.subSectionType]}
          </Text>
        </View>
        <Close style={{fontSize: '16px'}} onClick={handleRemove} />
      </View>
      <List>
        {items.map((item, index) => (
          <Cell
            key={index}
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              marginBottom: '10px',
            }}
          >
            <View style={{display: "flex"}}>
              <RefInput
                value={item}
                onChange={(e) => handleItemsChange(index, e.detail.value)}
                active={active}
              />
              <Button
                size='small'
                icon={<Minus />}
                onClick={() => handleRemoveItems(index)}
              />
            </View>
          </Cell>
        ))}
        <Cell key={-1}>
          <Button
            onClick={handleAddItems}
            size='small'
            icon={<Plus />}
          />
        </Cell>
      </List>
    </View>
  );
};

export default GenericMultipleSection;
